package com.threeti.mecool.web.controller.report;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.codehaus.jackson.map.ObjectMapper;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import com.threeti.mecool.core.application.report.ReportService;
import com.threeti.mecool.core.application.report.SupervisorTaskPerformanceRate;
import com.threeti.mecool.core.application.report.TaskPerformanceRate;
import com.threeti.mecool.core.domain.model.basicdata.AdminDivisionLevelDeep;
import com.threeti.mecool.core.domain.model.plan.PlanJobResult;
import com.threeti.mecool.core.infrastructure.persistence.acl.UserRepository;
import com.threeti.mecool.core.infrastructure.persistence.plan.PlanJobResultRepository;
import com.threeti.mecool.framework.util.Lists;
import com.threeti.mecool.legacy.domain.model.basicdata.AdminDivisionLegacy;
import com.threeti.mecool.legacy.infrastructure.persistence.AdminDivisionLegacyRepository;
import com.threeti.mecool.web.util.RequestUtil;

@Controller
@RequestMapping("/report/storeVisitingTrack")
public class StoreVisitingTrackReportController {

	public static final Logger logger = LoggerFactory.getLogger(StoreVisitingTrackReportController.class);

	@Autowired
	private PlanJobResultRepository planJobResultRepo;

	@Autowired
	private ReportService rptService;

	@Autowired
	private AdminDivisionLegacyRepository adminDivLegRepo;
	
	@Autowired
	private UserRepository userRepository;

	@RequestMapping(value = "/reportList/{adminDivLevelDeep}.html")
	public String reportList(@PathVariable int adminDivLevelDeep, Map modelMap,HttpServletRequest request) {
		modelMap.put("adminDivLevelDeep", adminDivLevelDeep);
		modelMap.putAll(RequestUtil.getParameterMap(request));
		return "/report/storeVisitingTrack/reportList";
	}

	@RequestMapping(value = "/reportList/6/{customAdminDivAreaCode}.html")
	public String reportList1(@PathVariable String customAdminDivAreaCode,Map modelMap,HttpServletRequest request) {
		modelMap.put("adminDivLevelDeep",AdminDivisionLevelDeep.MECOOL_CUSTOMIZED_ADMINAREA.ordinal());
		modelMap.put("standardAdminDivAreaCode", customAdminDivAreaCode);
		modelMap.putAll(RequestUtil.getParameterMap(request));
		return "/report/storeVisitingTrack/reportList";
	}

	
	/**
	 * 省级查询
	 * @author Yuqi Chou
	 * @param standardAdminDivAreaCode
	 * @param modelMap
	 * @param request
	 * @return
	 * @version Oct 30, 2012  11:04:54 AM
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/reportList/1/{standardAdminDivAreaCode}.html")
	public String reportList2(@PathVariable String standardAdminDivAreaCode,Map modelMap,HttpServletRequest request) {
		
		Map<String, String> paramMap = RequestUtil.getParameterMap(request);
		
		//无法直视
		if (standardAdminDivAreaCode.equals("11000000") || standardAdminDivAreaCode.equals("12000000") || standardAdminDivAreaCode.equals("31000000") || standardAdminDivAreaCode.equals("50000000")) {
			return reportList3(standardAdminDivAreaCode, modelMap,request);
		}
		
		// 将异步操作转化为同步操作以满足地图绘制...
		List<TaskPerformanceRate> rates = rptService.storeVisitingTrackSummaryByProvince(standardAdminDivAreaCode,paramMap);
		modelMap.put("storeVisitingTracks", rates);// 汇总数据
		AdminDivisionLegacy adminDivLeg = adminDivLegRepo.findOne(standardAdminDivAreaCode);
		String provinceAdName = StringUtils.isEmpty(adminDivLeg.getParentProvinceAdName()) ? adminDivLeg.getName(): adminDivLeg.getParentProvinceAdName();
		modelMap.put("standardAdminDivAreaName", provinceAdName);
		modelMap.put("adminDivLevelDeep",AdminDivisionLevelDeep.CITY.ordinal());
		modelMap.put("mapZoomLevel", "10");// 8是一个相对合适的用于省市级别展示的ZOOM等级
		modelMap.put("standardAdminDivAreaCode", standardAdminDivAreaCode);
		return "/report/storeVisitingTrack/reportListCityMap";
	}

	
	/**
	 * 市级查询
	 * @author Yuqi Chou
	 * @param standardAdminDivAreaCode
	 * @param modelMap
	 * @param request
	 * @return
	 * @version Oct 30, 2012  11:03:25 AM
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/reportList/2/{standardAdminDivAreaCode}.html")
	public String reportList3(@PathVariable String standardAdminDivAreaCode,Map modelMap,HttpServletRequest request) {
		
		Map<String, String> paramMap = RequestUtil.getParameterMap(request);
//		List<SupervisorTaskPerformanceRate> rates = rptService.storeVisitingTrackSummaryByCity(standardAdminDivAreaCode,paramMap);
		
		List<SupervisorTaskPerformanceRate> rates = rptService.employLastStoreVisitingTrack(standardAdminDivAreaCode,paramMap);
		
		modelMap.put("storeVisitingTracks", rates);// 汇总数据
		modelMap.put("mapZoomLevel", "13");// 13是一个相对合适的用于城区级别展示的ZOOM等级
		modelMap.put("adminDivLevelDeep",AdminDivisionLevelDeep.DISTRICT_SUBURB.ordinal());

		try {
			
			
//			List<PlanJobResult> plannedStoresDetail;
//			List<PlanJobResult> actualStoresDetail;
//			plannedStoresDetail = planJobResultRepo.findByJobStatusAndChannelChannelCityAdCode(PlanJobResult.JOB_STATUS_NOT_FINISHED,standardAdminDivAreaCode);
//			actualStoresDetail = planJobResultRepo.findByJobStatusAndChannelChannelCityAdCode(PlanJobResult.JOB_STATUS_FINISHED,standardAdminDivAreaCode);
//			// 计划任务和实际任务均为0时候的处理(为了正确显示地图，必须要获取地理区域名字)->
//			if (CollectionUtils.isEmpty(plannedStoresDetail)) {
//				AdminDivisionLegacy adminDivLeg = adminDivLegRepo.findOne(standardAdminDivAreaCode);
//				String provinceAdName = StringUtils.isEmpty(adminDivLeg.getParentCityAdName()) ? adminDivLeg.getName(): adminDivLeg.getParentCityAdName();
//				modelMap.put("standardAdminDivAreaName", provinceAdName);
//			} else {
//				modelMap.put("standardAdminDivAreaName", plannedStoresDetail.get(0).getStoreChannelCityAdName());
//			}
//			// <-
			// 明细数据
//			modelMap.put("actualTasksDetail", actualStoresDetail);
//			modelMap.put("plannedTasksDetail", plannedStoresDetail);
			
			
			AdminDivisionLegacy adminDivLeg = adminDivLegRepo.findOne(standardAdminDivAreaCode);
			String provinceAdName = StringUtils.isEmpty(adminDivLeg.getParentCityAdName()) ? adminDivLeg.getName(): adminDivLeg.getParentCityAdName();
			modelMap.put("standardAdminDivAreaName", provinceAdName);

			
		} catch (Exception e) {
			e.printStackTrace();
		}

		modelMap.put("standardAdminDivAreaCode", standardAdminDivAreaCode);

		return "/report/storeVisitingTrack/reportListCityMap";
	}

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/reportList/3/{executorEmpId}/{standardAdminDivAreaCode}.html")
	public String reportList4(@PathVariable String executorEmpId,@PathVariable String standardAdminDivAreaCode, Map modelMap,HttpServletRequest request) {
		
		Map<String, String> params = RequestUtil.getParameterMap(request);
		
		String searchStartTime=params.get("searchStartTime");
		String searchEndTime=params.get("searchEndTime");
		
		DateTime dtStart = null;
		if(StringUtils.isEmpty(searchStartTime)){
			// within today->
			dtStart = new DateTime();
			dtStart = dtStart.withHourOfDay(0);
			dtStart = dtStart.withMinuteOfHour(0);
			dtStart = dtStart.withSecondOfMinute(0);
			dtStart = dtStart.withMillisOfSecond(0);
		}else{
			try {
				dtStart=new DateTime(DateUtils.parseDate(searchStartTime, new String[]{"yyyy-MM-dd HH:mm:ss"}));
			} catch (ParseException e) {
				dtStart = new DateTime();
			}
		}
		
		
		DateTime dtEnd = null;
		if(StringUtils.isEmpty(searchEndTime)){
			// within today->
			dtEnd = new DateTime();
			dtEnd = dtEnd.withHourOfDay(23);
			dtEnd = dtEnd.withMinuteOfHour(59);
			dtEnd = dtEnd.withSecondOfMinute(59);
			dtEnd = dtEnd.withMillisOfSecond(999);
		}else{
			try {
				dtEnd=new DateTime(DateUtils.parseDate(searchEndTime, new String[]{"yyyy-MM-dd HH:mm:ss"}));
			} catch (ParseException e) {
				dtEnd = new DateTime();
			}
		}
		
		
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		SimpleDateFormat sdf1=new SimpleDateFormat("yyyy-MM-dd");
		modelMap.put("dtStart",sdf1.format(dtStart.toDate()));
		modelMap.put("dtEnd", sdf1.format(dtEnd.toDate()));
		
		// <-
		List<PlanJobResult> executorDetails = planJobResultRepo.findByEmpIdAndChannelChannelCityAdCodeOrderByPlanJobStartTimeAndPlanTimeBetween(executorEmpId, standardAdminDivAreaCode,dtStart.toDate(), dtEnd.toDate());

		// 找不到数据时候的处理(为了正确显示地图和相关数据，必须要获取地理区域名字和其它信息)->
		if (CollectionUtils.isEmpty(executorDetails)) {
			AdminDivisionLegacy adminDivLeg = adminDivLegRepo.findOne(standardAdminDivAreaCode);
			String provinceAdName = StringUtils.isEmpty(adminDivLeg.getParentCityAdName()) ? adminDivLeg.getName(): adminDivLeg.getParentCityAdName();
			modelMap.put("standardAdminDivAreaName", provinceAdName);
		} else {
			modelMap.put("standardAdminDivAreaName", executorDetails.get(0).getStoreChannelCityAdName());
		}
		// <-
		
		
		try {
			modelMap.put("executorName",userRepository.findByEmployeeEmpId(Long.valueOf(executorEmpId)).getEmployee().getName());
		} catch (Exception e) {
		}
		
		
		modelMap.put("standardAdminDivAreaCode", standardAdminDivAreaCode);
		modelMap.put("executorEmpId", executorEmpId);
		modelMap.put("executorDetails", executorDetails);
		modelMap.put("mapZoomLevel", "13");// 13是一个相对合适的用于城区级别展示的ZOOM等级
		modelMap.put("adminDivLevelDeep",AdminDivisionLevelDeep.DISTRICT_SUBURB.ordinal());
		
		
		List locations=Lists.newArrayList();
		if (!CollectionUtils.isEmpty(executorDetails)) {
			PlanJobResult start = executorDetails.get(0);
			PlanJobResult end = executorDetails.get(executorDetails.size()-1);
			
			locations=rptService.findUserLoactions(sdf.format(start.getPlanJobStartTime()),
												   sdf.format(end.getPlanJobStartTime()),
												   userRepository.findByEmployeeEmpId(Long.valueOf(executorEmpId)).getLoginName());
		}
		
		
		ObjectMapper om=new ObjectMapper();
		try {
			modelMap.put("executorLocations",om.writeValueAsString(locations));
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return "/report/storeVisitingTrack/reportListExecutorDetailsCityMap";
	}

	@RequestMapping(value = "/reportListData/{adminDivLevelDeep}.html")
	public String reportListData(@PathVariable int adminDivLevelDeep,Map modelMap,HttpServletRequest request) {
		List<TaskPerformanceRate> rates = Lists.newArrayList();

		if (adminDivLevelDeep == AdminDivisionLevelDeep.PROVINCE.ordinal()) {
			rates = rptService.storeVisitingTrackSummaryByProvinceALL(new HashMap<String, String>());
		} else if (adminDivLevelDeep == AdminDivisionLevelDeep.MECOOL_CUSTOMIZED_ADMINAREA.ordinal()) {

			rates = rptService.storeVisitingTrackSummaryByCustomAreas();
		}
		modelMap.put("storeVisitingTracks", rates);
		modelMap.put("adminDivLevelDeep", adminDivLevelDeep);

		return "/report/storeVisitingTrack/reportListData";
	}
	
	/**
	 * 区域查询
	 * @author Yuqi Chou
	 * @param customAdminDivAreaCode
	 * @param modelMap
	 * @param request
	 * @return
	 * @version Oct 30, 2012  11:05:36 AM
	 */
	@RequestMapping(value = "/reportListData/6/{customAdminDivAreaCode}.html")
	public String reportListData1(@PathVariable String customAdminDivAreaCode,Map modelMap,HttpServletRequest request) {
		
		Map<String, String> paramMap = RequestUtil.getParameterMap(request);
		
		List<TaskPerformanceRate> rates = rptService.storeVisitingTrackSummaryByCustomArea(customAdminDivAreaCode,paramMap);

		modelMap.put("storeVisitingTracks", rates);
		modelMap.put("adminDivLevelDeep",AdminDivisionLevelDeep.PROVINCE.ordinal());
		modelMap.put("standardAdminDivAreaCode", customAdminDivAreaCode);

		return "/report/storeVisitingTrack/reportListData";
	}
	
}
